package com.ckjava.test.aop;

import com.alibaba.fastjson.JSON;
import com.ckjava.test.utils.HttpResponseUtils;
import com.ckjava.xutils.ArrayUtils;
import com.ckjava.xutils.CollectionUtils;
import com.ckjava.xutils.ExceptionUtils;
import com.ckjava.xutils.StringUtils;
import com.ckjava.xutils.http.HttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Enumeration;

@Aspect
@Component
@Order(2)
public class AutoLogAop extends AopBase {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Around("autoLog()")
    public Object handleLog(ProceedingJoinPoint joinPoint) {
        // 记录下请求内容
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] methodArgs = joinPoint.getArgs();

        // 目标方法的处理
        try {
            long begin = System.currentTimeMillis();
            Object returnObj = joinPoint.proceed(methodArgs);
            long consumeTime = System.currentTimeMillis() - begin;

            logger.info(JSON.toJSONString(CollectionUtils.asHashMap(
                    ArrayUtils.toArray("classMethod", "methodArgs", "return", "consumeTime"),
                    ArrayUtils.toArray(classMethod, methodArgs, returnObj, consumeTime + " ms"))));

            return returnObj;
        } catch (Throwable e) {
            logger.error(JSON.toJSONString(CollectionUtils.asHashMap(
                    ArrayUtils.toArray("classMethod", "methodArgs", "exception"),
                    ArrayUtils.toArray(classMethod, methodArgs, ExceptionUtils.getExceptionMsg(e)))));

            return null;
        }
    }

}
